<?php
class Books extends CI_Model{
	
	function get_books($conditions = array()){
		$where = "book.status = 1";
		if(!empty($conditions['grade'])){
			$where .= " AND book.grade = '{$conditions['grade']}' ";
		}
		if(!empty($conditions['semester'])){
			$where .= " AND book.semester = '{$conditions['semester']}' ";
		}
		if(!empty($conditions['subject_id'])){
			$where .= " AND book.subject_id = '{$conditions['subject_id']}' ";
		}
		$sql = "SELECT book.id,book.title,book.image,book.grade,book.semester,s.name AS subject_name,s.id AS subject_id FROM {$this->db->dbprefix}b_book AS book ";
        $sql .= "LEFT JOIN {$this->db->dbprefix}b_subject AS s ON(s.id=book.subject_id) ";
		$sql .= "WHERE $where ORDER BY book.grade ASC, book.semester ASC ";
		$result = $this->db->query($sql)->result_array();
		return array("list" => $result);
	}

	//章节练习题目列表
	function get_book_chapter_list($limit = 0, $offset = 0, $conditions = array()){
		$where = "c.status = 1 ";
		if(!empty($conditions['book_id'])){
			$where .= " AND c.book_id = '{$conditions['book_id']}' ";
		}
		$sql = "SELECT SQL_CALC_FOUND_ROWS c.id, c.title, count(t.id) AS total FROM {$this->db->dbprefix}b_book_chapter AS c ";
		$sql .= "LEFT JOIN {$this->db->dbprefix}tk_topics AS t ON(t.chapter_id=c.id AND t.status = 1) ";
		$sql .= "WHERE $where GROUP BY c.id ORDER BY id ASC ";
		if($limit > 0 || $offset > 0){
		   $sql .= "LIMIT $limit, $offset";
		}
		$result = $this->db->query($sql)->result_array();
		$row_num =  $this->db->query('SELECT FOUND_ROWS() as row_num;')->row_array();
		return array("count" => $row_num['row_num'], "result" => $result);
	}

	function return_all_caregory_list(){
		$sql = "SELECT * FROM {$this->db->dbprefix}book_category WHERE status = 1";
		$result = $this->db->query($sql)->result_array();
		return $result;
	}

	function get_book_list_by_category($category_id, $limit = 0, $offset = 10){
		$sql = "SELECT SQL_CALC_FOUND_ROWS * FROM {$this->db->dbprefix}books WHERE status=1 AND category_id='{$category_id}' ORDER BY id DESC LIMIT $limit, $offset";
		$result = $this->db->query($sql)->result_array();
		$row_num =  $this->db->query('SELECT FOUND_ROWS() as row_num;')->row_array();
		return array("count" => $row_num['row_num'], "list" => $result);
	}
}